package dao

import (
	"advertising/internal/dal"
	"advertising/internal/models"
	"context"
	"strings"
	"time"

	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type PublishScheduleLog struct{}

func (PublishScheduleLog) Create(ctx context.Context, db *gorm.DB, scheduleID, merchantID, robotName string, count int64) (err error) {
	m := dal.Use(db).PublishScheduleLog
	var data models.PublishScheduleLog
	data.ID, _ = helper.UUID{}.String()
	data.ScheduleID = scheduleID
	data.MerchantID = merchantID
	data.RobotName = robotName
	data.Count = count
	data.CreatedAt = time.Now().Unix()
	m.WithContext(ctx).Create(&data)
	return
}

func (PublishScheduleLog) List(ctx context.Context, db *gorm.DB, scheduleID, robotName string, page, limit int) (res []*models.PublishScheduleLog, count int64, err error) {
	m := dal.Use(db).PublishScheduleLog
	tx := m.WithContext(ctx)
	if scheduleID != "" {
		if strings.Contains(scheduleID, ",") {
			tx = tx.Where(m.ScheduleID.In(strings.Split(scheduleID, ",")...))
		} else {
			tx = tx.Where(m.ScheduleID.Eq(scheduleID))
		}
	}
	if robotName != "" {
		if strings.Contains(robotName, ",") {
			tx = tx.Where(m.RobotName.In(strings.Split(robotName, ",")...))
		} else {
			tx = tx.Where(m.RobotName.Eq(robotName))
		}
	}
	return tx.FindByPage(Offset(page, limit))
}

func (PublishScheduleLog) UpdateCount(ctx context.Context, db *gorm.DB, scheduleID, robotName string, count int) (err error) {
	if scheduleID == "" && robotName == "" {
		return
	}
	m := dal.Use(db).PublishScheduleLog
	tx := m.WithContext(ctx)
	if scheduleID != "" {
		if strings.Contains(scheduleID, ",") {
			tx = tx.Where(m.ScheduleID.In(strings.Split(scheduleID, ",")...))
		} else {
			tx = tx.Where(m.ScheduleID.Eq(scheduleID))
		}
	}
	if robotName != "" {
		if strings.Contains(robotName, ",") {
			tx = tx.Where(m.RobotName.In(strings.Split(robotName, ",")...))
		} else {
			tx = tx.Where(m.RobotName.Eq(robotName))
		}
	}
	tx.Update(m.Count, count)
	return
}
